<?php
class Items_model extends CI_Model {

	public function __construct()
	{
		$this->load->database();
	}
	
	public function get_items($size = FALSE, $price_from = '', $price_to = '', $name = '', $code = '', $season = 0 )
	{
		if ( empty( $size ) && empty( $price_from ) && empty( $price_to ) && empty( $name )  && empty( $code ) && empty( $season )) {
			$this->db->select('items.*, sizes.*, images.* ');
			$this->db->distinct();
			$this->db->from('items');
			$this->db->join('sizes', 'items.id = sizes.item_id');
			$this->db->join('images', 'items.id = images.item_id');
			$query = $this->db->get_where();
			return $query->result_array();
		}
		
		$where = array();
		$where['amount'] = $where_one = "`sizes`.`amount` > 0";

		if( !empty( $price_from )) {
			$where['price_from'] = $where_one = "`sizes`.`price` >= ".$price_from;
		}
		if( !empty( $price_to )) {
			$where['price_to'] = $where_one = "`sizes`.`price` <= ".$price_to;
		}
		
		if ( !empty( $size ) ) {
			$from = $to = array();
			foreach ($size as $a_size) {
				$range = explode('-', $a_size);
				$from[] = $range[0];
				if(isset($range[1])) {
					$to[] = $range[1];
				}
			}
			$where_one = "`sizes`.`size` IN (" . implode( ',', $from ) . ")";
			if( count($to) > 0 ) {
				$where_one .= " OR `sizes`.`size_to` IN (" . implode( ',', $to ) . ")";
			}
			$where['size'] = $where_one;
		}
		
		if( !empty( $name )) {
			$where['name'] = $where_one = '`items`.`name` LIKE "%' . $name . '%"';
		}
		
		if( !empty( $season ) && count( $season ) > 0) {
			$this->db->join('collections', 'collections.id = items.collection_id');
			$where['season'] = $where_one = '`collections`.`season_id` IN(' . implode( ',', $season ) . ')';
		}
		
		if( !empty( $code )) {
			$where['code'] = $where_one = '`images`.`file_name` LIKE "%' . $code . '%"';
		}

		if( count( $where ) == 1 ) {
			$where_str = $where_one;
			$this->db->where( $where_str );
		} else {
			if( !empty( $where['size'] )) {
				$where['size'] = "(" . $where['size'] .")";
			}
			$where_str = implode( ' AND ', $where );
			$this->db->where( $where_str );
		}
		
		$this->db->select('items.*, sizes.*, images.* ');
		$this->db->distinct();
		$this->db->from('items');
		$this->db->join('sizes', 'items.id = sizes.item_id');
		$this->db->join('images', 'items.id = images.item_id');

		$query = $this->db->get_where();
//		$query_str = $this->db->last_query();
//		print($query_str);
		return $query->result_array();
	}
}
